var my_media = null;// 音频播放器
var words = {}; //生词表
var cigeng = {}; //词根
var rooturl = "";
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;

function include(file){
//加载css javascript
   var files = typeof file == "string" ? [file] : file;
   for (var i = 0; i < files.length; i++)
   {
       var name = files[i].replace(/^\s|\s$/g, "");
       var att = name.split('.');
       var ext = att[att.length - 1].toLowerCase();
       var isCSS = ext == "css";
       var tag = isCSS ? "link" : "script";
       var attr = isCSS ? " type='text/css' rel='stylesheet' " : " type='text/javascript' ";
       var link = (isCSS ? "href" : "src") + "='" + name + "'";
       if ($(tag + "[" + link + "]").length == 0){
           s = "<" + tag + attr + link + "></" + tag + ">";           
           $("head").append(s);
           
           log("tag " + tag);
           log("attr <" + tag + attr);
           log("link <" + tag + attr + link);
           
           log("include "+"<" + tag + attr + link + "></" + tag);
       }
   }
}

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 log(filename+fileref);
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

function debug(){
  $("#logs").toggle();
}

function log(text){
//显示console
  $("#logs").prepend("<li>"+text+"</li>"); 
}

function playAudio(src) {
// 播放音频
  log("playaudio " + src);
  if(isChrome)
    return;
  function onSuccess() {
    //log("playAudio():Audio Success");
  }
  
  // 创建Media对象出错后调用的回调函数
  function onError(error) {
    //log('code: '    + error.code    + ' ' + error.message );
  }
  if(my_media!=null){
    my_media.release();
  }
  // 从目标文件创建Media对象
  my_media = new Media(src, onSuccess, onError);

  // 播放音频
  my_media.play();
}

function onclick(){
//点击单词回调
  word = $(this).addClass("clicked").html().toLowerCase();  
  //save
  count = 1;
  if(words[word]){
    count = words[word].count+1;
  }
  wordobject = {time:new Date().getTime(),count:count,word:word}
  storeWord(word,wordobject)
  
  $("#clicked [word='"+word+"']").remove();
  $("#clicked").prepend( wordstring(wordobject) );
  
  log("onclick "+word);
  url = "http://www.iciba.com/"+word;
  //if($.browser.chrome)
  //  url = "help.htm"
  $.ajax({
    url:url,
    success:function(data){
      mp3 = "http://dict.youdao.com/dictvoice?audio="+word;
      playAudio(mp3);
      $data = $(data) 
      
      yinbiao = "["+$(data).find("[lang='EN-US']:last").text()+"]"
      
      $cls = $data.find(".caption:first")
      if($cls.length>0){
        chinese = $cls.find(".text_blue").text()
        cixin = $cls.find(".st .tips_content").text()        
        $cls.find("span").remove()
        explan = $cls.text().replace(/\s+/g," ").substr(1)
      }else{
        explan = $data.find("[sid='netmeans_0_0']").text().replace(/\s+/g," ").substr(1)
        chinese = ""
        cixin = ""
        yinbiao=""
      }
      ss = word+"\n"+explan+"\n"+cixin+" "+yinbiao+" "+chinese;
      if( cigeng[word] ){ 
        ss = ss +"\n"+cigeng[word].explan
      }
      alert(ss);      
    },
    error:function(){
      log('onclick load error');
    }
  }); 
  log("onclick end");    
}

function makeWord(){
//给单词加回调
  $list = $("#list");
  $list.find(":not(iframe)").andSelf().contents().filter(function() {
      return this.nodeType == 3;
  }).each(function(){
    text = this.nodeValue.replace(/([\w'-]+)/g,"<span class='word'>$1</span>");          
    $(this).replaceWith(text);
  });
  $('.word').die().live("click",onclick);
}

function loadFML(){
//载入http://m.fmylife.com/
  log("loadFML");
  $list = $("#list");
  url= "http://m.fmylife.com/";
  //if($.browser.chrome)
  //  url = "fml.htm"
  $.ajax({
      url:url,
      //dataType:'html',
      success:function(data) {
        log("load success " );
        $("#loading").hide();
        var $html = $(data);
        index = 1;
        $html.find("p.text").each(function() {
            $list.append( "<p class='post'>"+index+" "+$(this).html()+"</p>" );
            index=index+1;
        });
        //$list.append(" alive ahead aside ");
        makeWord();
      },
      error:function(){
        log('init load error');
      }
  });
}

function storeWord(key,value){
    words[key]=value;
    localStorage.setItem( "words",JSON.stringify(words) );
}

function wordstring(word){
  return "<div word='"+word.word+"'><span>"+word.count+"</span> <span class='word'>"+word.word+"</span></div>  "
}

function showWords(){
  //生词表
  if( localStorage.getItem("words")!=null ){
    words = JSON.parse(localStorage.getItem("words"));
  }
  wordArray = []
  for(x in words){
    wordArray.push(words[x])
    wordArray.sort(function(a,b){return b.time-a.time});
  }
  if(wordArray.length==0)
    return;
  
  for(x in wordArray){
    if(x>50){
        delete words[wordArray[x]];
    }else{
      $("#clicked").append( wordstring(wordArray[x]) );
    }
  }
}

function init(){
  //
  log("v1.2");
  //
  showWords();
  //
  $.getJSON(rooturl+"cigeng.json",function(result){
    cigeng=result;
    log(cigeng['ahead'].explan);
  });
  //css
  //include(rooturl+"main.css");
  loadjscssfile(rooturl+"main.css","css")
  //fml
  loadFML();  
}

$(init);